#include<iostream>
#include<cassert>
#include<unistd.h>
#include<string>
#include<unistd.h>
#include<arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>

class UdpSocket
{
  private:
    int _sockfd;
  public:
    UdpSocket():_sockfd(-1){}
    ~UdpSocket()
    {
      Close();
    }

    //接口
    bool Socket()
    {
      _sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
      if(_sockfd<0)
      {
        perror("socket error");
        return false;
      }
      return true;
    }

    bool Bind(std::string &ip,uint16_t port)
    {
      struct sockaddr_in addr;
      addr.sin_family = AF_INET;
      addr.sin_port = htons(port);
      addr.sin_addr.s_addr = inet_addr(ip.c_str());
      socklen_t len = sizeof(struct sockaddr_in);

      int ret = bind(_sockfd,(struct sockaddr*)&addr,len);
      if(ret<0)
      {
        perror("bind error");
        return false;
      }
      return true;
    }

    bool Recvfrom(std::string *body,std::string *peer_ip=NULL,uint16_t *peer_port=NULL)
    {
      struct sockaddr_in peer;
      socklen_t len = sizeof(struct sockaddr_in);
      char buf[1024]={0};
      ssize_t ret = recvfrom(_sockfd,buf,1024,0,(struct sockaddr*)&peer,&len);
      if(ret<0)
      {
        perror("recvfrom error");
        return false;
      }
      if(peer_ip!=NULL)
      {
       *peer_ip = inet_ntoa(peer.sin_addr);
      }
      if(peer_port!=NULL)
      {
        *peer_port = ntohs(peer.sin_port);
      }
      body->assign(buf,ret);
      return true;
    }

    bool Send(const std::string &data,const std::string &peer_ip,uint16_t peer_port)
    {
      struct sockaddr_in addr;
      addr.sin_family = AF_INET;
      addr.sin_port = htons(peer_port);
      addr.sin_addr.s_addr = inet_addr(peer_ip.c_str());
      socklen_t len = sizeof(struct sockaddr_in);

      ssize_t ret = sendto(_sockfd,data.c_str(),data.size(),0,(struct sockaddr*)&addr,len);
      if(ret<0)
      {
        perror("sendto error");
        return false;
      }
      return true;
    }

    bool Close()
    {
      if(_sockfd!=-1)
      {
        close(_sockfd);
        _sockfd=-1;
      }
      return true;
    }
};
